import { defineStore } from 'pinia'
import { computed } from 'vue'
import { useContainerStore } from './containerStore'

export const useInsightStore = defineStore('insight', () => {
  const containerStore = useContainerStore()
  
  // 计算平均有效性评分
  const averageEffectivenessScore = computed(() => {
    const completedContainers = containerStore.completedContainers
    if (completedContainers.length === 0) return 0
    
    const totalScore = completedContainers.reduce((sum, container) => {
      return sum + (container.evaluation?.effectivenessScore || 0)
    }, 0)
    
    return (totalScore / completedContainers.length).toFixed(1)
  })
  
  // 计算时间预估准确率
  const timeEstimationAccuracy = computed(() => {
    const completedContainers = containerStore.completedContainers
    if (completedContainers.length === 0) return 0
    
    const accuracySum = completedContainers.reduce((sum, container) => {
      const estimatedTime = container.estimatedTime
      const actualTime = container.actualTime
      
      // 计算准确率：1 - |实际时间-预估时间|/预估时间
      // 如果准确率为负，则视为0
      const accuracy = Math.max(0, 1 - Math.abs(actualTime - estimatedTime) / estimatedTime)
      return sum + accuracy
    }, 0)
    
    return ((accuracySum / completedContainers.length) * 100).toFixed(1)
  })
  
  // 获取标签统计
  const tagStatistics = computed(() => {
    const completedContainers = containerStore.completedContainers
    const tagStats = {
      positive: {},
      negative: {}
    }
    
    completedContainers.forEach(container => {
      if (!container.evaluation) return
      
      // 统计正向标签
      container.evaluation.positiveTags.forEach(tag => {
        if (!tagStats.positive[tag]) {
          tagStats.positive[tag] = {
            count: 0,
            totalScore: 0,
            avgScore: 0
          }
        }
        
        tagStats.positive[tag].count++
        tagStats.positive[tag].totalScore += container.evaluation.effectivenessScore
        tagStats.positive[tag].avgScore = (tagStats.positive[tag].totalScore / tagStats.positive[tag].count).toFixed(1)
      })
      
      // 统计负向标签
      container.evaluation.negativeTags.forEach(tag => {
        if (!tagStats.negative[tag]) {
          tagStats.negative[tag] = {
            count: 0,
            totalScore: 0,
            avgScore: 0
          }
        }
        
        tagStats.negative[tag].count++
        tagStats.negative[tag].totalScore += container.evaluation.effectivenessScore
        tagStats.negative[tag].avgScore = (tagStats.negative[tag].totalScore / tagStats.negative[tag].count).toFixed(1)
      })
    })
    
    return tagStats
  })
  
  // 获取高效行为洞察
  const effectiveBehaviorInsights = computed(() => {
    const stats = tagStatistics.value
    const insights = []
    
    // 分析正向标签
    Object.entries(stats.positive).forEach(([tag, data]) => {
      if (data.count >= 2 && data.avgScore >= 4) {
        insights.push({
          type: 'positive',
          tag,
          message: `当你使用「${tag}」时，任务有效性平均提高到${data.avgScore}星！这是个值得坚持的好方法。`,
          score: data.avgScore,
          count: data.count
        })
      }
    })
    
    // 分析负向标签
    Object.entries(stats.negative).forEach(([tag, data]) => {
      if (data.count >= 2 && data.avgScore <= 3) {
        insights.push({
          type: 'negative',
          tag,
          message: `「${tag}」标签关联的任务平均评分较低（${data.avgScore}星），建议寻找改进方法。`,
          score: data.avgScore,
          count: data.count
        })
      }
    })
    
    return insights.sort((a, b) => {
      // 正向洞察优先，然后按评分和出现次数排序
      if (a.type !== b.type) return a.type === 'positive' ? -1 : 1
      if (a.type === 'positive') return b.score - a.score || b.count - a.count
      return a.score - b.score || b.count - a.count
    })
  })
  
  return {
    averageEffectivenessScore,
    timeEstimationAccuracy,
    tagStatistics,
    effectiveBehaviorInsights
  }
})